package com.xpec.c4.service.group.datalayer.infinispan;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 给infinispan用的ThreadPoolExecutor,代替默认,因为原来的异常无法输出.
 * @author lipeilin
 *
 */
public class InfinispanThreadPoolExecutor extends ThreadPoolExecutor {
	
	private static final Log log = LogFactory.getLog(InfinispanThreadPoolExecutor.class);

	public InfinispanThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
				threadFactory);
	}

	@Override
	protected void afterExecute(Runnable r, Throwable t) {
		if(r instanceof RunnableScheduledFuture){
			RunnableScheduledFuture<?> task = (RunnableScheduledFuture<?>)r;
			if(task.isDone()){
				try {
					task.get();
				} catch (InterruptedException e) {
				} catch (ExecutionException e) {
					log.error(r,e);
				} catch (CancellationException e) {
				}
				remove(r);
			}
		}
		else if(r instanceof FutureTask){
			FutureTask<?> task = (FutureTask<?>)r;
			if(task.isDone()){
				try {
					task.get();
				} catch (InterruptedException e) {
				} catch (ExecutionException e) {
					log.error(r,e);
				} catch (CancellationException e) {
				}
				remove(r);
			}
		}
		if(t!=null){
			log.error(r,t);
		}
		super.afterExecute(r, t);
	}

}
